# This controller handles the login/logout function of the site.  
class SessionsController < ApplicationController
  # Be sure to include AuthenticationSystem in Application Controller instead
  # include AuthenticatedSystem

  before_filter :login_required, :except => [:new, :create]

  # render new.rhtml
  def new
    #render :action => 'new'
  end

  def create
    logout_keeping_session!
    user = User.authenticate(params[:login], params[:password])
    if user
      # Protects against session fixation attacks, causes request forgery
      # protection if user resubmits an earlier form using back
      # button. Uncomment if you understand the tradeoffs.
      # reset_session
      self.current_user = user
      new_cookie_flag = (params[:remember_me] == "1")
      handle_remember_cookie! new_cookie_flag
      redirect_back_or_default('/projects')
      flash[:notice] = "登录成功"
    else
      #note_failed_signin
      @login       = params[:login]
      @remember_me = params[:remember_me]
      #render :action => 'new'
      flash[:notice] = "用户名/密码 错误!"
      redirect_to :action => 'new'
    end
  end

  def destroy
    logout_killing_session!
    flash[:notice] = "您已经注销."
    redirect_back_or_default('/')
  end

  def edit
    @user = User.find(params[:id], :conditions => ["id = ?", current_user.id])
  end

  def update
    params[:user][:role_ids] ||= []
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      flash[:notice] = "User was successfully updated."
      redirect_to :action => 'edit', :id => @user
    else
      flash[:error] = 'Unsuccessful. Try again.'
      redirect_to :action => 'edit', :id => @user
    end

  end

  def change_password
    @user = User.find(params[:id])

    return unless request.post?

    if (params[:password] == params[:password_confirmation])
      current_user.password_confirmation = params[:password_confirmation]
      current_user.password = params[:password]
      flash[:notice] = current_user.save ? "Password changed" : "Password not changed. Try again."
    else
      flash[:error] = "Password mismatch. Try again."
      @old_password = params[:old_password]
    end
  end

protected
  # Track failed login attempts
  def note_failed_signin
    flash[:error] = "Couldn't log you in as '#{params[:login]}'"
    logger.warn "Failed login for '#{params[:login]}' from #{request.remote_ip} at #{Time.now.utc}"
  end
end
